﻿#pragma once

#include <thread>
#include <atomic>
#include <string>

#include "uWS.h"



// 静态库
#pragma comment(lib, "uv_a.lib")
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "Userenv.lib")
#pragma comment(lib, "Psapi.lib")
#ifdef _DEBUG
#	pragma comment(lib, "zlibstaticd.lib")
#else
#	pragma comment(lib, "zlibstatic.lib")
#endif

namespace uWS {

	class uHttpWebSocket
	{
	private:
		uHttpWebSocket(uHttpWebSocket&);
		uHttpWebSocket operator=(uHttpWebSocket&);
	public:
		uHttpWebSocket();
		virtual ~uHttpWebSocket();
		// 单例
		static uHttpWebSocket& Instance();

	public:
		// 初始化
		bool Init(int iPort = 3000, std::string strWebRoot = "./wwwRoot", std::string strDefaultTarget = "index.html");
		// 反初始化
		bool UnInit();
		// 获取端口
		int GetPort() { return miPort; }

		// 获取本地地址
		void GetLocalAddr(std::vector<std::string>& addrVec);
		void GetLocalAddrQt(std::vector<std::string>& addrVec);
		void GetLocalAddrWindows(std::vector<std::string>& addrVec);

		// 向所有连接的客户端发送数据
		bool SendToAllClient(std::string strData);
	protected:
		// 运行循环线程
		//static void __stdcall RunThread(uHttpWebSocket *);
		void RunThreadImplement();

		// websocket响应函数
		virtual void onMessage(uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode);
		// http响应函数
		void onHttpRequest(HttpResponse *res, HttpRequest req, char *data, size_t length, size_t remainingBytes);
	protected:
		std::vector<std::thread> mRunThreadVec;
		std::vector<uWS::Hub *> mServerVec;
		// 中断标志
		//volatile bool mInterrupted;

		// 本地监听端口
		int miPort;
		// web页面本地根目录
		std::string mstrWebRoot;
		// web页面的默认主页名称
		std::string mstrDefaultTarget;

		std::atomic<int> mRuningThreadCount;
	};


}